﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.LanguageResource;
using System.Data.Entity;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportRawForms
{
    public partial class ReportRawDetailForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.StandardRawBll standardSelfBll = new BLL.StandardRawBll();
        BLL.ReportRawBll reportRawBll = new BLL.ReportRawBll();
        BLL.ReportRawResultBll reportRawResultBll = new BLL.ReportRawResultBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        List<ReportRawResult> _resList = new List<ReportRawResult>();
        int _optionNO;
        ReportRaw _editEntity;
        Action _InitGrid;
        OJCB4Entities db = new OJCB4Entities();
        public ReportRawDetailForm(Action InitGrid)   //新建
        {
            InitializeComponent();
            _optionNO = 1;
            this.Text = ResourceOverall.CreateStr;
            this.textEdit_loginUserName.Text = LoginUserUtil.LoginUser.EmpName;
            _InitGrid = InitGrid;
        }


        public ReportRawDetailForm(ReportRaw reportRaw, Action InitGrid)    //编辑
        {
            InitializeComponent();

            _optionNO = 2;
            ReportRaw report = db.ReportRaws.Find(reportRaw.ReportRawID);
            _editEntity = report;
            this.Text = ResourceOverall.EditStr;
            _InitGrid = InitGrid;
            InitFormWhenEdit(report);
        }


        private void ReportRawDetailForm_Load(object sender, EventArgs e)
        {
            var goodsList = toolBll.GetRawGoodList();
            this.lookUpEditGoodsName.Properties.DataSource = goodsList;
        }

        private void InitFormWhenEdit(ReportRaw reportRaw)
        {
            lookUpEditGoodsName.EditValue = reportRaw.GoodsID;
            textEdit_SampleNO.Text = reportRaw.SampleNO;
            textEdit_BatchNumber.Text = reportRaw.BatchNumber;
            textEdit_ProductionUnit.Text = reportRaw.ProductionUnit;
            textEdit_SampleSendPerson.Text = reportRaw.SampleSendPerson;
            dateEdit_SendDate.DateTime = reportRaw.SendDate;
            //checkEdit_IsUrgent.Checked = reportRaw.IsUrgent;
            textEdit_Conclusion.Text = reportRaw.Conclusion;
            textEdit_TotalVehicle.Text = reportRaw.TotalVehicle;
            textEdit_PlateNumber.Text = reportRaw.PlateNumber;
            textEdit_Remark.Text = reportRaw.Remark;
            textEdit_loginUserName.Text = reportRaw.LoginUser.EmpName;
            _resList = reportRaw.ReportRawResults.ToList();
            this.dataGridControl.DataSource = _resList;
            this.lookUpEditGoodsName.Enabled = false;
        }




        private void lookUpEditGoodsName_EditValueChanged(object sender, EventArgs e)
        {
            //读取标准添加到grid
            string id = Convert.ToString(this.lookUpEditGoodsName.EditValue);
            _resList = reportRawBll.GetEmptReusltListByGoodsID(id);
            this.dataGridControl.DataSource = _resList;
            gridView1.BeginDataUpdate();
            try
            {
                gridView1.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            }
            finally
            {
                gridView1.EndDataUpdate();
            }

        }

        private void ButtonItem_save_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //关闭编辑状态
            this.gridView1.CloseEditor();
            //判空
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                lookUpEditGoodsName.Focus();
                return;
            }
            if (this.dateEdit_SendDate.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                dateEdit_SendDate.Focus();
                return;
            }

            if (_optionNO == 1)
            {
                ReportRaw reportRaw = new ReportRaw();
                reportRaw.ReportRawID = Guid.NewGuid().ToString();
                reportRaw.BatchNumber = this.textEdit_BatchNumber.Text;
                reportRaw.GoodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
                //reportRaw.IsUrgent = this.checkEdit_IsUrgent.Checked;
                reportRaw.PlateNumber = this.textEdit_PlateNumber.Text;
                reportRaw.ProductionUnit = this.textEdit_ProductionUnit.Text;
                reportRaw.Remark = this.textEdit_Remark.Text;
                reportRaw.SampleNO = this.textEdit_SampleNO.Text;
                reportRaw.SampleSendPerson = this.textEdit_SampleSendPerson.Text;
                reportRaw.SendDate = this.dateEdit_SendDate.DateTime;
                reportRaw.Conclusion = this.textEdit_Conclusion.Text;
                reportRaw.TotalVehicle = this.textEdit_TotalVehicle.Text;
                reportRaw.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                reportRaw.ReportRawResults = _resList;
                reportRaw.AddDateTime = DateTime.Now;
                //样品编号判断重复
                int count= reportRawBll.LoadEntities(m => m.SampleNO == reportRaw.SampleNO).Count();
                if (count>0)
                {
                    XtraMessageBox.Show("报告编号重复!");
                    return;
                }
                ReportRaw resReport = reportRawBll.AddEntity(reportRaw);
                if (resReport != null)
                {
                    _InitGrid();
                    XtraMessageBox.Show(ResourceOverall.CreateSucceed);
                    this.Close();

                }
            }
            if (_optionNO == 2)
            {
                _editEntity.BatchNumber = this.textEdit_BatchNumber.Text;
                _editEntity.GoodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
                //_editEntity.IsUrgent = this.checkEdit_IsUrgent.Checked;
                _editEntity.PlateNumber = this.textEdit_PlateNumber.Text;
                _editEntity.ProductionUnit = this.textEdit_ProductionUnit.Text;
                _editEntity.Remark = this.textEdit_Remark.Text;
                _editEntity.SampleNO = this.textEdit_SampleNO.Text;
                _editEntity.SampleSendPerson = this.textEdit_SampleSendPerson.Text;
                _editEntity.SendDate = this.dateEdit_SendDate.DateTime;
                _editEntity.Conclusion = this.textEdit_Conclusion.Text;
                _editEntity.TotalVehicle = this.textEdit_TotalVehicle.Text;
                _editEntity.ReportRawResults = _resList;
                _editEntity.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                bool result = EditReport(_editEntity);
                if (result)
                {
                    _InitGrid();
                    XtraMessageBox.Show(ResourceOverall.EditSucceed);
                    this.Close();
                }
            }


        }



        //private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        //{
        //    //int col = e.ColumnIndex;
        //    //int row = e.RowIndex;
        //    //ReportRawResult result = _resList[row];
        //    //string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(result.MinValue, result.MaxValue, result.TestValue);
        //    //_resList[row].Conclusion = res;
        //    ////if (res=="不合格")
        //    ////{
        //    ////    dataGridView1.Rows[row].Cells[col].Style.BackColor = Color.Red;
        //    ////}
        //    ////else
        //    ////{
        //    ////    dataGridView1.Rows[row].Cells[col].Style.BackColor = Color.White;
        //    ////}
        //    //this.dataGridControl.Refresh();
        //}

        private void ButtonItem_addTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show("样品名称必选!The name of the sample must be selected !");
                return;
            }
            FlyHorse.LIMS.WinApp.OtherForms.AddResultForm addResultForm = new OtherForms.AddResultForm(AddTestItem);
            addResultForm.ShowDialog();
        }

        private void AddTestItem(TestItem testItem, string minValue, string maxVlaue)
        {

            ReportRawResult res = new ReportRawResult();
            res.Basis = testItem.Basis;
            res.ChineseName = testItem.ChineseName;
            res.FormOrder = testItem.Order;
            res.ReportRawResultID = Guid.NewGuid().ToString();
            res.MinValue = minValue;
            res.MaxValue = maxVlaue;
            res.TestItemID = testItem.TestItemID;
            res.Unit = testItem.Unit;
            _resList.Add(res);
            string name = this.dataGridControl.DataMember;
            dataGridControl.RefreshDataSource();
            this.dataGridControl.Refresh();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            string id = (string)this.gridView1.GetRowCellValue(e.RowHandle, "ReportRawResultID");
            string minValue = null;
            string maxValue = null;
            string testValue = null;
            if (this.gridView1.GetRowCellValue(e.RowHandle, "MinValue") != null)
            {
                minValue = this.gridView1.GetRowCellValue(e.RowHandle, "MinValue").ToString();
            }
            if (this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue") != null)
            {
                maxValue = this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue").ToString();
            }
            if (this.gridView1.GetRowCellValue(e.RowHandle, "TestValue") != null)
            {
                testValue = this.gridView1.GetRowCellValue(e.RowHandle, "TestValue").ToString();
            }

            if (!String.IsNullOrEmpty(minValue))
            {
                Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
                minValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
            }
            if (!String.IsNullOrEmpty(maxValue))
            {
                Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
                maxValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
            }
            if (!String.IsNullOrEmpty(testValue))
            {
                try
                {
                    Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                    testValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                }
                catch (Exception ex)
                {
                    this.gridView1.SetRowCellValue(e.RowHandle, "TestValue", null);
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }
            string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(minValue, maxValue, testValue);
            _resList.Where(m => m.ReportRawResultID == id).First().Conclusion = res;
            this.dataGridControl.Refresh();
        }

        private void ButtonItem_DelTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportRawResultID") != null)
            {
                DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    string id = (string)this.gridView1.GetFocusedRowCellValue("ReportRawResultID");
                    _resList = (List<ReportRawResult>)this.dataGridControl.DataSource;
                    ReportRawResult res = _resList.Where(m => m.ReportRawResultID == id).First();
                    DeleteReportResult(_resList, res);
                    //_resList.Remove(_resList.Where(m => m.ReportRawResultID == id).First());
                    this.dataGridControl.RefreshDataSource();
                }
            }
            else
            {
                XtraMessageBox.Show(ResourceOverall.SelectNull);
            }

        }



        private bool EditReport(ReportRaw report)
        {
            foreach (var item in report.ReportRawResults)
            {
                item.ReportRawID = report.ReportRawID;
            }
            db.Entry(report).State = EntityState.Modified;
            int count = db.SaveChanges();
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }



        private void DeleteReportResult(List<ReportRawResult> reslutList, ReportRawResult res)
        {
            var entity = db.ReportRawResults.Where(m => m.ReportRawResultID == res.ReportRawResultID).FirstOrDefault();
            if (entity != null)
            {
                db.ReportRawResults.Remove(entity);
                db.SaveChanges();
                reslutList.Remove(res);
            }
            else
            {
                reslutList.Remove(res);
            }
        }

    }
}